#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // 添加这一行以包含 sleep 函数的声明
#define MAX 100
pthread_mutex_t mutex;
pthread_cond_t cond ;

void *thread1(void *);
void *thread2(void *);

int i=1;
int main(void){
    pthread_t t_a;
    pthread_t t_b;
    pthread_mutex_init (&mutex,NULL); //互斥量的初始化
    pthread_cond_init (&cond,NULL); //条件变量的初始化
    pthread_create(&t_a,NULL,thread1,(void *)NULL); //创建进程 t_a/
    pthread_create(&t_b,NULL,thread2,(void *)NULL); //创建进程 t_b/
    pthread_join(t_b, NULL); //等待进程 t_b 结束*
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    exit(0);
}

void *thread1(void *flag)
{
    for(i=1;i<MAX;i++){
        pthread_mutex_lock(&mutex); //锁住互斥量*/
        if (i%9==0)
            pthread_cond_signal(&cond); //条件改变，发送信号，通知 t_b 进程*/
        else
            printf("In thread1:%d\n",i);
        pthread_mutex_unlock(&mutex); //解锁互斥量*/
        sleep(1);
    }
}

void *thread2(void *flag)
{
    while(i<MAX)
    {
        pthread_mutex_lock(&mutex);
        printf("In thread2 before wait\n");
        if (i%9!=0)
            pthread_cond_wait(&cond,&mutex); //等待并释放 mutex*/
        printf("In thread2 after wait\n");
        if (i%9==0)
            printf("In thread2:%d\n",i);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

